package com.GlobalPaint.app.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.util.LruCache;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.GlobalPaint.app.R;
import com.GlobalPaint.app.bean.EventBusben;
import com.GlobalPaint.app.bean.PushGis;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.bean.TalentBean;
import com.GlobalPaint.app.ui.Home.HomeFragment;
import com.GlobalPaint.app.ui.Laborer.LaborerFragment;
import com.GlobalPaint.app.ui.Login.Login;
import com.GlobalPaint.app.ui.MessageFragment.MessegeActivity;
import com.GlobalPaint.app.ui.Mine.MineFragment;
import com.GlobalPaint.app.ui.Mine.Personal.PersonalActivity;
import com.GlobalPaint.app.ui.location.LocationFragment;
import com.GlobalPaint.app.utils.CommUtility;
import com.GlobalPaint.app.utils.Constants;
import com.GlobalPaint.app.utils.DataManager;
import com.GlobalPaint.app.utils.TabEntity;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.utils.SPUtils;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.gyf.barlibrary.ImmersionBar;
import com.jzy.message.service.MsfService;
import com.jzy.message.util.SoundManager;
import com.jzy.message.util.xmpp.Const;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.common.inter.ITagManager;
import com.umeng.message.tag.TagManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    MainActivity thisMainActivity = null;
    private CommonTabLayout mTabLayout;
    private long mBackPressedTime;
    String youmengText = "";
    String youmengTicker = "";
    private String[] mTitles;
    private int[] mIconUnselectIds;
    private int[]  mIconSelectIds;
    private ArrayList<CustomTabEntity> mTabEntities;
    private ArrayList<Fragment> fragments;
    private TalentBean bean;
    private LocationClient mLocationClient;
    private LocationClient getmLocationClient1;
    LocationClientOption option;
    private PushGis gis;
    private String city;
    private SPUtils spUtils;
    SoundManager snd;
    int qq;

    private LocalReceiver localReceiver;
    private IntentFilter intentFilter;
    private LocalBroadcastManager localBroadcastManager;


    private BDLocationListener mBDLocationListener;
    private BDLocationListener mBDLocationListener1;
    public static final int GET_FUBIAO = 0x0003; //上传经纬度
    public static final int GET_TOKEN = 0x0004;//上传地址和推送的token
    public static final int GET_CITY = 0x0001; //获取青岛市
    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case GET_FUBIAO:
                    String url = Constants.JASON_SERVICE_URL + "Gis/save?userid=" + DataManager.userEntity.getUserId();
                    DataManager.getInst().postHttpRequestJsonClass(url, DataManager.userEntity.getCookie(), gis, TalentBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            bean = (TalentBean) o;
                            if (bean.getStatus() == 1) {
                                Log.d("mainActivity", "onSuccess:");
                            }
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {

                        }
                    });
                    break;
                case GET_CITY:
                    getmLocationClient1 = new LocationClient(MainActivity.this);
                    mBDLocationListener1 = new MyBDLocationListener1();
                    // 声明定位参数
                    option = new LocationClientOption();
                    option.setCoorType("bd09ll");// 设置返回定位结果是百度经纬度 默认gcj02
                    option.setIsNeedAddress(true);// 设置定位结果包含地址信息
                    // 设置定位参数
                    getmLocationClient1.setLocOption(option);
                    // 启动定位
                    getmLocationClient1.start();
                    // 注册监听
                    getmLocationClient1.registerLocationListener(mBDLocationListener1);
                    break;
                case GET_TOKEN:
                    String url2 = Constants.JASON_SERVICE_URL + "user/uploadAliasInfo?userId="
                            + DataManager.userEntity.getUserId() + "&userName=" + DataManager.userEntity.getUserName()
                            + "&deviceToken=" + DataManager.deviceToken + "&alias=" + city + "&sessionId=" +
                            DataManager.userEntity.getCookie();
                    Log.d("mainActivity", "url2==" + url2);
                    Log.d("mainActivity", "GET_TOKEN==" + DataManager.deviceToken + "城市名称==" + city);
                    DataManager.getInst().getHttpRequestJsonClass(url2, DataManager.userEntity.getCookie(), TalentBean.class, new DataManager.Callback() {
                        @Override
                        public void onSuccess(Object o) {
                            bean = (TalentBean) o;
                            if (bean.getStatus() == 1) {
                                final String tag = "zone"+String.valueOf(DataManager.userEntity.zoneId);
                                DataManager.mPushAgent.getTagManager().add(new TagManager.TCallBack() {
                                            @Override
                                            public void onMessage(boolean b, ITagManager.Result result) {
                                                Log.d("umTag", result.jsonString);
                                    }
                                }, tag);
                                Log.d("mainActivity", "GET_TOKEN:+onSuccess");
                            }
                        }

                        @Override
                        public void onFailure(ReturnStatusResultEntity error) {

                        }
                    });
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CommUtility.verifyStoragePermissions(this);//添加高版本的权限
        thisMainActivity = this;
        youmengTicker = getIntent().getStringExtra("youmengTicker");
        youmengText = getIntent().getStringExtra("youmengText");
        Log.d("jjjjjjj", "onCreate: main");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Const.ACTION_NEW_MSG);
        localReceiver=new LocalReceiver();
        registerReceiver(localReceiver, intentFilter);
        spUtils = new SPUtils(DataManager.context, "login");
        EventBus.getDefault().register(this);
        if (DataManager.userEntity == null) {
                SPUtils spUtils = new SPUtils(DataManager.context, "login");
                spUtils.remove("user");
                //退出时清除缓存
                DataManager.lruCache = new LruCache<>(10);
                Intent intent1 = new Intent(MainActivity.this, Login.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent1);
                finish();
        }else if(DataManager.userEntity.getfNickName()==null){
            Intent intent2 = new Intent(MainActivity.this, PersonalActivity.class);
            intent2.putExtra("main","main");
            startActivityForResult(intent2,1);
            finish();
        }
        mhandler.sendEmptyMessage(GET_CITY);
        initView();
        if(youmengTicker !=null && youmengTicker != ""){
            Intent intent=new Intent(MainActivity.this, MessegeActivity.class);
            intent.putExtra("youmengTicker",youmengTicker);
            intent.putExtra("youmengText",youmengText);
            startActivity(intent);
        }
        putGis();
        startXMPPService();
    }

    //点击退出 后移除mLocationClient
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void FirstEvent(EventBusben message) {
        String msg = message.getNr();

        if (msg == "tuichu") {
            mLocationClient.stop();
            stopXMPPService();        }
    }

    private void putGis() {
        //回调 获取坐标
        // 声明LocationClient类
        mLocationClient = new LocationClient(MainActivity.this);
        mBDLocationListener = new MyBDLocationListener();
        // 声明定位参数
        option = new LocationClientOption();
        option.setCoorType("bd09ll");// 设置返回定位结果是百度经纬度 默认gcj02
        option.setScanSpan(120000);// 设置发起定位请求的时间间隔 单位ms
        option.setIsNeedAddress(true);// 设置定位结果包含地址信息
        option.setNeedDeviceDirect(true);// 设置定位结果包含手机机头 的方向
        // 设置定位参数
        mLocationClient.setLocOption(option);
        // 启动定位
        mLocationClient.start();
        // 注册监听
        mLocationClient.registerLocationListener(mBDLocationListener);
    }

    private void initView() {
        mTabLayout = (CommonTabLayout) findViewById(R.id.main_tabLayout);
        mTitles = new String[]{
                "首页", "用工", "定位", "我的"
        };

        mIconUnselectIds = new int[]{
                R.drawable.icon_home, R.drawable.icon_laborer, R.drawable.icon_wz,
                R.drawable.icon_mine,
        };

        mIconSelectIds = new int[]{
                R.drawable.icon_home2, R.drawable.icon_laborer2, R.drawable.icon_wz1,
                R.drawable.icon_mine1};
        fragments = new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new LaborerFragment());
        fragments.add(new LocationFragment());
        // fragments.add(new MessageFragment());
        fragments.add(new MineFragment());

        mTabEntities = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }
        mTabLayout.setTabData(mTabEntities, this, R.id.main_viewPager, fragments);
    }

    @Override
    public void onBackPressed() {

        boolean isDoubleClick = true;// BaseApplication.get(AppConfig.KEY_DOUBLE_CLICK_EXIT, true);

        if (isDoubleClick) {
            long curTime = SystemClock.uptimeMillis();
            if ((curTime - mBackPressedTime) < (3 * 1000)) {
                finish();
            } else {
                mBackPressedTime = curTime;
                Toast.makeText(this, "再次点击退出", Toast.LENGTH_LONG).show();
            }
        } else {
            finish();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    // 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    private class MyBDLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            // 非空判断
            if (location != null) {
                // 根据BDLocation 对象获得经纬度以及详细地址信息
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                String address = location.getAddrStr();
                String city1 = location.getCity();
                Log.i("123456相同页面1分钟也发", "address:" + address + " latitude:" + latitude
                        + " longitude:" + longitude + "---" + "city1" + city1);
                if (latitude <= 0 || longitude <= 0) {
                    return;
                }
                city = city1;

                gis = new PushGis();
                gis.setLat(String.valueOf(latitude));
                gis.setLng(String.valueOf(longitude));
                gis.setUserid(DataManager.userEntity.getUserId());
                mhandler.sendEmptyMessage(GET_FUBIAO);
            }
        }
    }

    private class MyBDLocationListener1 implements BDLocationListener {
        PushAgent mPushAgent = PushAgent.getInstance(getApplicationContext());

        @Override
        public void onReceiveLocation(BDLocation location) {
            // 非空判断
            if (location != null) {
                String city1 = location.getCity();
                Log.d("123456789相同页面就发一次", "handleMessage: " + city);
                city = city1;
                DataManager.city = city;
                mhandler.sendEmptyMessage(GET_TOKEN);
                mPushAgent.removeAlias(city, "qiLian", new UTrack.ICallBack() {
                    @Override
                    public void onMessage(boolean isSuccess, String message) {

                    }
                });

                mPushAgent.addAlias(city, "qiLian", new UTrack.ICallBack() {
                    @Override

                    public void onMessage(boolean isSuccess, String message) {

                    }

                });

                getmLocationClient1.stop();

            }
        }
    }

    private void startXMPPService() {
        Intent intent = new Intent(thisMainActivity, MsfService.class);
        startService(intent);
    }
    public void stopXMPPService(){
        final Intent intent = new Intent();
        intent.setAction("MESSAGE.OPFIRESERVICE");
        stopService(intent);
    }
    //接受广播 回调mess页面
    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            Log.d("guanbao", "onReceive: ");
            //添加语音提示
            snd = new SoundManager(getApplicationContext());
            qq = snd.load(com.jzy.message.R.raw.qq);
            try {
                Thread.sleep(1000);
                snd.play(qq);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ImmersionBar.with(this).destroy(); //不调用该方法，如果界面bar发生改变，在不关闭app的情况下，退出此界面再进入将记忆最后一次bar改变的状态
    }
}
